<template>
    <div class="users">
        <el-row justify="start">
            <el-col :xs="18" :sm="14" :md="11" :lg="8" :xl="4">
                <el-input placeholder="请输入用户名" clearable v-model="queryInfo.query" @clear="getUserList" size="large">
                    <template #append>
                        <el-button :icon="Search" @click="getUserList" />
                    </template>
                </el-input>
            </el-col>
            <el-col :span='3'>
                <el-button type="primary" @click="addDialogVisible=true" size="large">添加用户</el-button>
            </el-col>
        </el-row>
        <el-table :data="userData.users" stripe fit style="width: 100%" border>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="username" label="姓名"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="mobile" label="电话"></el-table-column>
            <el-table-column prop="role_name" label="角色"></el-table-column>
            <el-table-column label="状态">
                <template v-slot="data">
                    <el-switch v-model="data.row.mg_state" @change="userStateChange(data.row)" />
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200px">
                <template v-slot="scope">
                    <el-button type="primary" :icon="EditPen" @click="showEditDialog(scope.row)" />
                    <el-button type="danger" :icon="Delete" @click="removeUserById(scope.row.id)" />
                    <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                        <el-button type="warning" :icon="Setting" @click="showRolesDialog(scope.row)" />
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
        <el-config-provider :locale="zhCn">
            <el-pagination v-model:pageSize="queryInfo.pagesize" :total="userData.total"
                v-model:currentPage="queryInfo.pagenum" :page-sizes="[2, 3, 5, 10]" @current-change="getUserList"
                @size-change="getUserList" layout="total, sizes, prev, pager, next, jumper" background
                hide-on-single-page />
        </el-config-provider>
        <el-dialog title="添加用户" v-model="addDialogVisible" width="40%" @close="addFormRef.resetFields()">
            <el-form label-width="25%" ref="addFormRef" :model="userInfo" :rules="rules">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userInfo.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="userInfo.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userInfo.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="userInfo.mobile"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addUser(addFormRef)">确 定</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog title="编辑用户信息" v-model="editDialogVisible" width="40%" @close="userInfo={}">
            <el-form label-width="25%" :model="userInfo" :rules="rules" ref="editFormRef">
                <el-form-item label="用户名" prop="username">
                    <el-input :value="userInfo.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userInfo.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="userInfo.mobile"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editUser(editFormRef)">确 定</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog title="分配角色" v-model="setRolesDialogVisible" @close="userInfo={}" width="40%">
            <el-form label-width="25%" :model="userInfo">
                <el-form-item label="用户名" prop="username">
                    <el-input :value="userInfo.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="当前角色" prop="role_name">
                    <el-input :value="userInfo.role_name" disabled></el-input>
                </el-form-item>
                <el-form-item label="新角色">
                    <el-select v-model="selectRoleId" placeholder="请选择">
                        <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="setRolesDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveRolesInfo">确 定</el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>
<script setup>
    import {
        ElRow, ElCol,
        ElInput, ElButton, ElSwitch, ElTooltip, ElSelect, ElOption,
        ElTable, ElTableColumn,
        ElPagination,
        ElConfigProvider, 
        ElDialog, ElMessage, ElMessageBox,
        ElForm, ElFormItem
    } from "element-plus"
    import zhCn from 'element-plus/lib/locale/lang/zh-cn'  
    import {
        Setting,
        EditPen,
        Delete,
        Search
    } from '@element-plus/icons-vue'
    import {
        yonghulb,
    yonghuzt,
    tianjiayh,
    yonghuxx,
    shanchuyh,
    jiaoshelb,
    fenpeijs,
    } from "@/tools/ajax.js"
    import { reactive, ref } from "vue"
    import { useRules } from "@/tools/utils"
    const userData = reactive({})  
    const queryInfo = reactive({  
        query: "",   
        pagenum: 1,   
        pagesize: 3   
    })
    async function getUserList() {
        const res = await yonghulb(queryInfo)
        if (res.meta.status != 200) {
            return ElMessage.error(res.meta.msg);
        }
        ElMessage.success(res.meta.msg);
        userData.total = res.data.total;
        userData.users = res.data.users;
    }
    getUserList()
    const addDialogVisible = ref(false) 
    const addFormRef = reactive({}) 
    const userInfo = ref({}) 
    const { nameRule, pasRule, emailRule, mobileRule } = useRules()
    const rules = { 
        username: nameRule,
        password: pasRule,
        email: emailRule,
        mobile: mobileRule
    }
    async function addUser(form) {
        form.validate(async bool => {
            if (!bool) return ElMessage.warning("输入有误");
            console.log(userInfo.value);
            const { meta: res } = await tianjiayh(userInfo.value)
            console.log(res);
            if (res.status != 201) return ElMessage.error(res.msg);
            ElMessage.success(res.msg);
            addDialogVisible.value = false;
            getUserList() 
        })
        
    }
    async function userStateChange(data) {
        const res = await yonghuzt({
            uId: data.id,
            type: data.mg_state
        })
        console.log(data, res)
        if (res.meta.status !== 200) {
            data.mg_state = !data.mg_state
            return ElMessage.error('更新用户状态失败!')
        }
        return ElMessage.success('更新用户状态成功!')
    }
    const editDialogVisible = ref(false)
    const editFormRef = reactive(null)
    function showEditDialog(data) {
        editDialogVisible.value = true
        console.log(data);
        userInfo.value = data
    }
    async function editUser(form) {
        form.validate(async bool => {
            if (!bool) return ElMessage.warning("输入有误");
            console.log(userInfo);
            var { meta: res } = await yonghuxx(userInfo.value)
            console.log(res);
            if (res.status != 200) return ElMessage.error(res.msg);
            ElMessage.success(res.msg)
            editDialogVisible.value = false; 
            getUserList()  
        })
        
    }
    async function removeUserById(id) {
        const confirmRusult = await ElMessageBox.confirm('此操作将永久删除此用户, 是否继续?', '永久删除该用户', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch(err => err)
        console.log(confirmRusult)
        if (confirmRusult !== 'confirm') {
            return ElMessage.info('已经取消了删除')
        }
        console.log(id);
        const res = await shanchuyh({id})
        console.log(res)
        if (res.meta.status !== 200) {
            return ElMessage.error(res.meta.msg)
        }
        ElMessage.success(res.meta.msg)
        this.getUserList()
    }
    const setRolesDialogVisible = ref(false) 
    const rolesList = reactive([]) 
    const selectRoleId = ref("")
    async function showRolesDialog(data) {
        userInfo.value = data
        selectRoleId.value = ''
        var res = await jiaoshelb()
        if (res.meta.status != 200) {
            return ElMessage.error(res.meta.msg)
        }
        rolesList.splice(0)
        rolesList.push(...res.data)
        setRolesDialogVisible.value = true
    }
    async function saveRolesInfo() {
        if (!selectRoleId.value) return setRolesDialogVisible.value = false;
        console.log(selectRoleId.value, userInfo.value.id);
        var { meta: res } = await fenpeijs({
            uid: userInfo.value.id,
            rid: selectRoleId.value
        })
        console.log(res);
        if (res.status != 200) return ElMessage.error(res.msg);
        ElMessage.success(res.msg);
        setRolesDialogVisible.value = false; 
        getUserList() 
    }
    // #endregion
</script>
<style scoped lang="scss">
    .el-table {
        margin-top: 15px;
    }

    .el-pagination {
        margin-top: 15px;
    }

    .el-input,
    .el-select {
        width: 80%;
    }
</style>